package com.dk.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.domain.TCarDTO;
import com.dk.entity.TAdminDTO;
import com.dk.feign.VehicleServiceFeign;
import com.dk.util.IdWorker;
import com.dk.data.Result;
import com.dk.em.ConstantEnum;
import com.dk.pojo.TOrder;
import com.dk.service.ITOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/orderController")
@Api(value="订单接口文档")
public class OrderController {

    @Autowired
    private ITOrderService itOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VehicleServiceFeign vehicleServiceFeign;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @ApiOperation(value = "增加订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "TOrder", value = "订单实体类", required = true,
                    paramType = "query")
    })
    @PostMapping
    public Result addOrder(TOrder tOrder){
        IdWorker idWorker = new IdWorker();
        tOrder.setOutTradeNo(idWorker + "");
        boolean b =  itOrderService.insertOrder(tOrder);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(b);
    }

    @ApiOperation(value = "根据id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "订单id", required = true, paramType = "path")
    })
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable("id") Long id){
        TOrder order = itOrderService.getById(id);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(order);
    }

    @ApiOperation(value = "根据用户查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token值", required = true, paramType = "path")
    })
    @GetMapping("findByAdmin/{token}")
    public Result findByAdmin(@PathVariable("token") String token){
        //序列化  只支持 string  hash 类型
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        QueryWrapper wrapper = new QueryWrapper<TOrder>();
        wrapper.eq("admin_id",tAdminDTO.getId());
        List<TOrder> list = itOrderService.list(wrapper);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(list);
    }

    //支付定金
    @ApiOperation(value = "支付定金")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token值", required = true, paramType = "path"),
            @ApiImplicitParam(name = "id",value = "车辆id", required = true, paramType = "path")
    })
    @GetMapping("toPay/{token}/{id}")
    public String toPay(@PathVariable("token") String token,@PathVariable("id") String id){
        //序列化  只支持 string  hash 类型
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        Result<TCarDTO> tCarDTOResult = vehicleServiceFeign.selectById(Long.valueOf(id));
        TCarDTO tCarDTO = tCarDTOResult.getResult();
        BigDecimal price = tCarDTO.getGuidedPrice();
        String s = "0.2";
        BigDecimal decimal = new BigDecimal(s);
        BigDecimal decimal1 = price.multiply(decimal);

        TradeController tradeController = new TradeController();
        IdWorker idWorker = new IdWorker();
        long l = idWorker.nextId();
        String WIDout_trade_no = Long.toString(l);
        String WIDtotal_amount = decimal1 + "";
        String WIDsubject = tCarDTO.getName();
        String WIDbody = "定金交付";

        TOrder order = new TOrder();
        //已付定金
        order.setStatus("1");
        order.setOutTradeNo(WIDout_trade_no);
        order.setAdminId(tAdminDTO.getId().toString());
        order.setCarId(id);
        order.setPayment(new BigDecimal(tCarDTO.getGuidedPrice().toString()));
        order.setSourceType("1");

        Message<TOrder> message = MessageBuilder.withPayload(order).build();
        //发送mq异步延时消息
        rocketMQTemplate.syncSend("carOrder",message,3000,16);

        boolean b = itOrderService.save(order);
        if (b){
            String result = tradeController.toAliPay(WIDout_trade_no, WIDtotal_amount, WIDsubject, WIDbody);
            return result;
        }
        return "付款失败";
    }

    //修改状态已完成交易
    @ApiOperation(value = "修改支付状态为已完成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "订单id", required = true, paramType = "path")
    })
    @GetMapping("update/{id}")
    public Result update(@PathVariable("id") Long id){
        TOrder order = itOrderService.getById(id);
        order.setStatus("2");
        boolean b = itOrderService.updateById(order);
        if (b){
            return Result.bulid(ConstantEnum.SUCCESS).setResult("修改成功");
        }
        return Result.bulid(ConstantEnum.ERROR).setResult("修改失败");
    }
}
